This document gives a few suggestions to analyse a dataset composed by a set of geographic coordinates that have an associated numeric value.
It considers the population of 925 cities in the UK. This example dataset is provided in the R maps library and is available on this Github repository. Basically it looks like the table beside.
# Libraries
library(tidyverse)
library(hrbrthemes)
library(kableExtra)
options(knitr.table.format = "html")
library(viridis)
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/18_ListGPSCoordinatesWithValue.csv", header=T)
# show data
data %>% head(5) %>% kable() %>%
kable_styling(bootstrap_options = "striped", full_width = F)| lat | long | pop | name |
|---|---|---|---|
| 51.65 | -3.14 | 10146 | Abercarn-Newbridge |
| 51.72 | -3.46 | 33048 | Aberdare |
| 57.15 | -2.10 | 184031 | Aberdeen |
| 51.83 | -3.02 | 14251 | Abergavenny |
| 53.28 | -3.58 | 17819 | Abergele |
# Get the world polygon and extract UK
library(maps)
UK <- map_data("world") %>% filter(region=="UK")
# Easy to make it interactive!
library(plotly)
# plot
p=data %>%
arrange(pop) %>%
mutate( name=factor(name, unique(name))) %>%
mutate( mytext=paste("City: ", name, "\n", "Population: ", pop, sep="")) %>% # This prepare the text displayed on hover.
# Makte the static plot calling this text:
ggplot() +
geom_polygon(data = UK, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
geom_point(aes(x=long, y=lat, size=pop, color=pop, text=mytext, alpha=pop) ) +
scale_size_continuous(range=c(1,15)) +
scale_color_viridis(option="inferno", trans="log" ) +
scale_alpha_continuous(trans="log") +
theme_void() +
ylim(50,59) +
coord_map() +
theme(legend.position = "none")
ggplotly(p, tooltip="text")A work by Yan Holtz for data-to-viz.com